import { ipcMain } from "electron";
import { readSimpleConfigFileAllLines } from "@elec/main/util/file-utils.ts";
import { getAssetPath } from "@elec/main/util/assets.ts";
import type { LocalProjectItem } from "@common/local-project.types.ts";
import { mergeSingleNode, scanProjects } from "@elec/main/modules/local-project/local-project.service.ts";
import fs from "node:fs";

(() => {
  const getExcludes = async () => {
    const excludeList = await readSimpleConfigFileAllLines(getAssetPath("config/local-project.exclude.txt"));
    return excludeList.reduce(
      (acc, it) => {
        acc[it] = 1;
        return acc;
      },
      {} as Record<string, number>,
    );
  };

  ipcMain.handle("localProject.scan", async (_, folder: string) => {
    const p: LocalProjectItem = { key: folder, title: folder, path: folder };
    if (!fs.existsSync(folder)) return p;
    const excludes = await getExcludes();
    await scanProjects(p, excludes);
    mergeSingleNode(p);
    return p;
  });
})();
